package cn.yinyu.queue.module.ecg.service.callingscreen;

import cn.yinyu.queue.framework.common.pojo.PageResult;
import cn.yinyu.queue.module.ecg.controller.admin.checktype.vo.CheckTypePageReqVO;
import cn.yinyu.queue.module.ecg.dal.dataobject.checktype.CheckTypeDO;
import cn.yinyu.queue.module.ecg.dal.dataobject.queue.QueueDO;
import cn.yinyu.queue.module.ecg.dal.dataobject.room.RoomDO;
import cn.yinyu.queue.module.ecg.dal.mysql.checktype.CheckTypeMapper;
import cn.yinyu.queue.module.ecg.dal.mysql.queue.QueueMapper;
import cn.yinyu.queue.module.ecg.dal.mysql.room.RoomMapper;
import cn.yinyu.queue.module.ecg.enums.QueueStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 排队 Service 实现类
 *
 * @author 垠域源码
 */
@Service
@Validated
@Slf4j
public class CallingScreenServiceImpl implements CallingScreenService {

    @Resource
    private QueueMapper queueMapper;

    @Resource
    private RoomMapper roomMapper;

    @Resource
    private CheckTypeMapper checkTypeMapper;

    BigScreenConfig bigScreenConfig;

    Map<Integer, Integer> mapCheckTypeVsDisplayColumn = null;

    Integer waitingFrom = 0;
    Integer passedFrom = 0;

    @Override
    public void setBigScreenConfig(BigScreenConfig bigScreenConfig) {
        this.bigScreenConfig = bigScreenConfig;
    }


    @Override
    public Map<Integer, List<String>> getDisplayColInfo() {
        CheckTypePageReqVO checkTypePageReqVO = new CheckTypePageReqVO();
        checkTypePageReqVO.setPageSize(-1);
        checkTypePageReqVO.setCallingColumn(-1); // 列号 -1 的不显示
        PageResult<CheckTypeDO> pageResult = checkTypeMapper.selectPageForCallingScreen(checkTypePageReqVO);
        Map<Integer, List<CheckTypeDO>> mapDisplayColName = pageResult.getList().stream().collect(Collectors.groupingBy(CheckTypeDO::getCallingColumn));
        mapCheckTypeVsDisplayColumn = pageResult.getList().stream().collect(Collectors.toMap(CheckTypeDO::getValue, item -> item.getCallingColumn()));

        Map<Integer, List<String>> _map = new HashMap<>();
        mapDisplayColName.keySet().forEach(key -> {
            _map.put(key, mapDisplayColName.get(key).stream().map(item->item.getName()).toList());
        });
        return _map;
    }

    @Override
    public Map<Integer, Map<Integer, List<QueueDO>>> callingData() {
        Map<Integer, Map<Integer, List<QueueDO>>> mapDisplayColQueue = new HashMap<>();
        int displayColCnt = (int) mapCheckTypeVsDisplayColumn.values().stream().distinct().count();
        for (int dispCol=0; dispCol<displayColCnt; dispCol++) {
            Map<Integer, List<QueueDO>> mapSoltQueueData = new HashMap<>();
            mapSoltQueueData.put(0, new ArrayList<>());
            mapSoltQueueData.put(1, new ArrayList<>());
            mapSoltQueueData.put(2, new ArrayList<>());
            mapDisplayColQueue.put(dispCol, mapSoltQueueData);
        }

        mapDisplayColQueue.values().stream().forEach(mapSlotQueue -> {
            mapSlotQueue.values().stream().forEach(queueList -> queueList.clear());
        });

        List<Integer> queueStatusList = new ArrayList<>();
        queueStatusList.add(QueueStatusEnum.READY.getStatus());
        queueStatusList.add(QueueStatusEnum.ONSTAGE.getStatus());
        queueStatusList.add(QueueStatusEnum.WAITING.getStatus());
        queueStatusList.add(QueueStatusEnum.RECALLED.getStatus());
        queueStatusList.add(QueueStatusEnum.PASSED.getStatus());
        List<QueueDO> queueDOList = queueMapper.getQueueByStatus( queueStatusList );
        queueDOList.stream().forEach(queueDO -> {
            Map<Integer, List<QueueDO>> mapSlotQueue = mapDisplayColQueue.get(mapCheckTypeVsDisplayColumn.get(queueDO.getBookCheckType()));
            List<QueueDO> soltList = mapSlotQueue.get(getDisplatSlotByQueueStatus(queueDO.getStatus()));
            soltList.add( queueDO );
        });

        mapDisplayColQueue.values().stream().forEach(mapSoltQueue -> mapSoltQueue.values().stream().forEach(
                slotQueueList -> slotQueueList.sort((o1, o2) -> {
                    if (null == o1.getSeqNum() && null == o2.getSeqNum()) {
                        return o1.getBookTimeslot() - o2.getBookTimeslot();
                    } else if (null != o1.getSeqNum() && null != o2.getSeqNum()) {
                        return o1.getSeqNum() - o2.getSeqNum();
                    } else if (null == o1.getSeqNum()) {
                        return 1;
                    } else {  //这里 必定 null == o2.getSeqNum()
                        return -1;
                    }
                })));
        return mapDisplayColQueue;
    }

    @Override
    public Map<Integer, List<QueueDO>> callingData2() {
        List<Integer> queueStatusList = new ArrayList<>();
        queueStatusList.add(QueueStatusEnum.READY.getStatus());
        queueStatusList.add(QueueStatusEnum.ONSTAGE.getStatus());
        List<QueueDO> listReady = queueMapper.getQueueByStatus( queueStatusList );

        queueStatusList.clear();
        queueStatusList.add(QueueStatusEnum.WAITING.getStatus());
        queueStatusList.add(QueueStatusEnum.RECALLED.getStatus());
        List<QueueDO> listWaiting = queueMapper.getPartialQueueByStatus( queueStatusList, waitingFrom, bigScreenConfig.waitingSize );
        if (listWaiting.size() < bigScreenConfig.waitingSize && waitingFrom != 0) {
            List<QueueDO> listWaiting_next = queueMapper.getPartialQueueByStatus( queueStatusList, 0, bigScreenConfig.waitingSize - listWaiting.size());
            listWaiting.addAll(listWaiting_next);
        }
        if (listWaiting.size() < bigScreenConfig.waitingSize) {
            waitingFrom = 0;
        } else {
            waitingFrom = listWaiting.getLast().getId() + 1;
        }

        queueStatusList.clear();
        queueStatusList.add(QueueStatusEnum.PASSED.getStatus());
        List<QueueDO> listPassed = queueMapper.getPartialQueueByStatus( queueStatusList, passedFrom, bigScreenConfig.passedSize );
        if (listPassed.size() < bigScreenConfig.passedSize && passedFrom != 0) {
            List<QueueDO> listPassed_next = queueMapper.getPartialQueueByStatus( queueStatusList, 0, bigScreenConfig.passedSize - listPassed.size());
            listPassed.addAll(listPassed_next);
        }
        if (listPassed.size() < bigScreenConfig.passedSize) {
            passedFrom = 0;
        } else {
            passedFrom = listPassed.getLast().getId();
        }

        log.info( " waitingFrom: {} passedFrom: {} ", waitingFrom, passedFrom);

        Map<Integer, List<QueueDO>> map = new HashMap<>();
        map.put(1, listReady);
        map.put(2, listWaiting);
        map.put(3, listPassed);
        return map;
    }

    @Override
    public List<QueueDO> getRoomQueue(String ip, List<Integer> statusList) {
        List<RoomDO> roomDOList = roomMapper.queueByIp(ip);
        Optional<RoomDO> optionalQueueDO = roomDOList.stream().filter(item -> StringUtils.hasLength(item.getIp())).findFirst();
        if (!optionalQueueDO.isPresent()) {
            return  new ArrayList<QueueDO>();
        }

        Long roomId = optionalQueueDO.get().getRoomId();
        List<QueueDO> queueDOList = queueMapper.getRoomQueueByStatus(roomId, statusList);
        return queueDOList;
    }

    private Integer getDisplatSlotByQueueStatus( Integer queueStatus ) {
        if (QueueStatusEnum.READY.getStatus() == queueStatus)
            return 0;
        else if (QueueStatusEnum.ONSTAGE.getStatus() == queueStatus)
            return 0;
        else if (QueueStatusEnum.WAITING.getStatus() == queueStatus)
            return 1;
        else if (QueueStatusEnum.RECALLED.getStatus() == queueStatus)
            return 1;
        else if (QueueStatusEnum.PASSED.getStatus() == queueStatus)
            return 2;
        else
            return 0;
    }

}
